package solutions;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2023-12-09
 * Time: 15:06
 */

//输入一个链表，输出该链表中倒数第k个结点。
public class Solution4 {
    public ListNode FindKthToTail(ListNode head, int k) {
        if(head == null || k < 0) {
            return null;
        }
        //快结点先走 k - 1步
        ListNode fast = head;
        ListNode slow = head;
        while (k > 0) {
            if(fast != null) {
                fast = fast.next;
            } else {
                return null;
            }
            k--;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
